package org.ThreadDemo.pool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {

    private static final Integer VALUE = 10;
    private int begin;
    private int end;
    private int result;


    public MyTask(int begin,int end) {
        this.begin = begin ;
        this.end = end ;
    }



    @Override
    protected Integer compute() {
        //判断 相加两个数是否大于10

        if((end -begin)<=VALUE) {
            //相加
            for (int i = begin; i <= end; i++) {
                result = result + i ;
            }
        } else {
                //进一步拆分
            int middle = (begin+end)/2 ;

            //拆分左边部分
            MyTask task01 = new MyTask(begin,middle);

            //拆分右边部分
            MyTask task02 = new MyTask(middle+1,end);

            task01.fork();
            task02.fork();

            result = task01.join() + task02.join();
        }




        return result;
    }
}
public class ForkJoinDemo1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        MyTask mytask = new MyTask(1,100);

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(mytask);

        //获取
        Integer result = forkJoinTask.get();
        System.out.println(result);
        forkJoinPool.shutdown();

    }
}




